import '../style/index.scss'
import {MenuOutlined} from '@ant-design/icons';
import {Divider, Pagination, Row, Col, Empty} from "antd";
import {Link, useLoaderData, useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import {Question, QuestionPage, QuestionQuery} from "../types/commonTypes.ts";
import {doGetQuestions} from "../api/apis.ts";
import {formatTime} from "../utils/format-utils.ts";
import HotTag from "../views/HotTag.tsx";
import {useLoginUser} from "../hooks/LoginHooks.tsx";

export async function loader({request}: any): Promise<QuestionPage> {
  const url = new URL(request.url);
  const tag = url.searchParams.get("tag") || '';
  const search = url.searchParams.get("search") || '';
  const creator = url.searchParams.get("creator") || '';
  const creatorName = url.searchParams.get("creator_name") || '';
  const queryParam: QuestionQuery = {
    tag, search, size: 20, page: 1, creator
  }
  const {code, data} = await doGetQuestions(queryParam);
  if (code == 200) {
    data.tag = tag;
    data.search = search;
    data.creator = creator;
    data.creatorName = creatorName;
    return data;
  }

  return {
    tag,
    search,
    records: [],
    total: "0",
    size: "0",
    current: "1",
    creatorName,
    creator
  };

}

export default function Index() {
  const data = useLoaderData() as QuestionPage;
  useEffect(() => {
    setPageData(data);
  }, [data]);
  const [pageData, setPageData] = useState(data);
  const handlePageChange = async (page: number, size: number) => {
    const queryParam: QuestionQuery = {
      tag: pageData.tag,
      search: pageData.search,
      size,
      page
    }
    const {code, data: newPageData} = await doGetQuestions(queryParam);
    if (code == 200) {
      setPageData({...pageData, ...newPageData})
    }
  }
  const navigate = useNavigate();
  const jumpToUserQuestions = (item: Question) => {
    if (item.creator != data.creator) {
      navigate(`/?creator=${item.creator}&creator_name=${item.creatorName}`);
    }
  }
  const user = useLoginUser();
  const getTitle = () => {
    if (data.creator && data.creatorName) {
      if (data.creator === user?.id + '') {
        return '我的问题';
      }
      return data.creatorName + '问题';
    }
    return <>发现 <MenuOutlined/></>
  }
  const isWidthScreen = document.documentElement.clientWidth > 800;
  return (
    <div className='index-page'>
      <Row>
        <Col span={isWidthScreen ? 18 : 24}>
          <h1 className='index-title'>{getTitle()}</h1>
          <div className='question-list'>
            {pageData?.records?.length ?
              pageData?.records?.map(
                (item: Question) => (
                  <div className='question-item' key={item.id}>
                    <Divider style={{'margin': 0}}/>
                    <Link className='question-item__title' to={`/question/index/${item.id}`}>
                      {item.title}
                    </Link>
                    <div className='question-item__author unselectable'>
                      <img onClick={() => jumpToUserQuestions(item)}
                           className='avatar' src={item.creatorAvatar} alt=""/>
                      <div onClick={() => jumpToUserQuestions(item)}
                           className='name'>{item.creatorName}</div>
                      <div className='data-idx time'>{formatTime(Number(item.gmtCreate))}</div>
                      <div className='data-idx margin-left--5'>{item.commentCount}个回复</div>
                      <div className='data-idx margin-left--5'>{item.viewCount}次浏览</div>
                    </div>
                  </div>)) :
              <div>
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
              </div>
            }
          </div>

          <Pagination size="small"
                      pageSize={parseInt(pageData.size || '0')}
                      total={pageData.total}
                      onChange={handlePageChange}
                      pageSizeOptions={['5', '10', '20', '50']}
                      showSizeChanger showQuickJumper/>

        </Col>
        {
            isWidthScreen && <Col span={6} style={{paddingTop: '70px'}}>
              <HotTag></HotTag>
            </Col>
        }
      </Row>
    </div>
  )
}